<template>
    <!--    用户搜索条件框-->
    <div class="cardContent">
        <a-form
                ref="formRef"
                name="advanced_search"
                class="ant-advanced-search-form"
                :model="searchData">
            <a-row :gutter="24">
                <a-col :span="8">
                    <a-form-item label="账号">
                        <a-input v-model:value="searchData.userCode" placeholder="请输入账号"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="用户名">
                        <a-input v-model:value="searchData.username" placeholder="请输入用户名"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="工号">
                        <a-input v-model:value="searchData.workNum" placeholder="请输入工号"></a-input>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="24" v-show="expand">
                <a-col :span="8">
                    <a-form-item label="手机号码">
                        <a-input v-model:value="searchData.phone" placeholder="请输入手机号码"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="状态">
                        <a-select v-model:value="searchData.status" placeholder="请选择状态">
                            <a-select-option :value="null">全部</a-select-option>
                            <a-select-option :value="0">在职</a-select-option>
                            <a-select-option :value="1">辞职</a-select-option>
                            <a-select-option :value="2">辞退</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="所属部门">
                        <a-select v-model:value="searchData.deptId"
                                  :options="departmentList"
                                  :field-names="{label:'name',value:'id'}"
                                  placeholder="请选择部门">
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="24" style="text-align: right">
                    <a-space>
                        <a-button type="primary" @click="load(1)">搜索</a-button>
                        <a-button type="default" @click="reset">重置</a-button>
                        <a style="font-size: 12px" @click="expand = !expand">
                            <template v-if="expand">
                                <UpOutlined/>
                                收起
                            </template>
                            <template v-else>
                                <DownOutlined/>
                                展开
                            </template>
                        </a>
                    </a-space>
                </a-col>
            </a-row>
        </a-form>
    </div>
    <!--    用户列表展示-->
    <div class="cardContent">
        <a-button type="primary" @click="openModal({})">新增</a-button>
        <a-table :dataSource="userList"
                 style="margin-top: 10px"
                 :columns="columns"
                 :pagination="false"
                 size="small"
                 bordered>
            <template #bodyCell="{text,record,index,column}">
                <template v-if="column.key == 'status'">
                    {{text == 0 ? "在职" : (text == 1 ? "辞职" : (text == 2 ? "辞退" : "停职"))}}
                </template>
                <template v-if="column.key == 'pic'">
                    <a-image
                            :src="text != undefined ? text : 'https://lyj-mall-bucket.oss-cn-guangzhou.aliyuncs.com/20230129/default.png'"
                            style="width: 32px;height: 32px"></a-image>
                </template>
                <template v-if="column.key == 'birthday'">
                    {{formatDate(text,'YYYY-MM-DD')}}
                </template>
                <a-space v-if="column.key == 'action'">
                    <a-button type="primary" ghost @click="getUserInfo(record.id)">详情</a-button>
                    <a-button type="primary" @click="openModal(record)">编辑</a-button>
                    <a-popconfirm
                            v-if="record.status == 0"
                            title="是否确认辞退改员工，赔偿3月工资?"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDismissed(record.id)"
                    >
                        <a-button type="danger">辞退</a-button>
                    </a-popconfirm>
                    <a-popconfirm
                            v-else
                            title="是否确认删除?"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button type="danger" ghost>删除</a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-table>
        <a-config-provider :locale="locale">
            <a-pagination style="margin-top: 10px; text-align: right"
                          v-model:current="pagination.current"
                          v-model:pageSize="pagination.pageSize"
                          show-quick-jumper
                          show-size-changer
                          :total="pagination.total"
                          :show-total="total => `总 ${total} 条数据`"
                          :page-size-options="pageSizeOptions"
                          @change="onChange"/>
        </a-config-provider>
    </div>
    <a-drawer
            v-model:visible="visible"
            class="custom-class"
            width="600"
            title="新增或编辑"
            placement="right"
            :footer-style="{textAlign: 'right'}"
    >
        <a-form
                :model="user"
                name="basic"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 20 }"
                autocomplete="off">
            <a-form-item label="用户账号" v-bind="validateInfos.userCode">
                <a-input v-model:value="user.userCode"/>
            </a-form-item>
            <a-form-item label="用户名" v-bind="validateInfos.username">
                <a-input v-model:value="user.username"/>
            </a-form-item>
            <a-form-item label="手机号码" v-bind="validateInfos.phone">
                <a-input v-model:value="user.phone"/>
            </a-form-item>
            <a-form-item label="邮箱" v-bind="validateInfos.email">
                <a-input v-model:value="user.email"/>
            </a-form-item>
            <a-form-item label="生日" v-bind="validateInfos.birthday">
                <a-config-provider :locale="locale">
                    <a-date-picker v-model:value="user.birthday"/>
                </a-config-provider>
            </a-form-item>

        </a-form>
        <template #footer>
            <a-space>
                <a-button type="default" @click="visible = false">取消</a-button>
                <a-button type="primary" @click="saveOrUpdate">保存</a-button>
            </a-space>
        </template>
    </a-drawer>
    <a-drawer
            v-model:visible="userInfoVisible"
            class="custom-class"
            width="800"
            title="用户信息详情"
            placement="right"
            :footer-style="{textAlign: 'right'}"
    >
        <a-descriptions layout="vertical" bordered>
            <template #title>
                <a-image :src="userInfo.pic" style="border-radius: 50%;height: 32px;width: 32px"></a-image>
                {{userInfo.username}}
            </template>
            <a-descriptions-item label="账号">{{userInfo.userCode}}</a-descriptions-item>
            <a-descriptions-item label="工号">{{userInfo.workNum}}</a-descriptions-item>
            <a-descriptions-item label="出生日期">{{formatDate(userInfo.birthday,'YYYY-MM-DD')}}</a-descriptions-item>
            <a-descriptions-item label="电话">{{userInfo.phone}}</a-descriptions-item>
            <a-descriptions-item label="邮箱" :span="2">{{userInfo.email}}</a-descriptions-item>
            <a-descriptions-item label="状态" :span="3">
                <a-badge v-if="userInfo.status == 0" status="processing" text="在职"/>
                <a-badge v-if="userInfo.status == 1" status="warning" text="离职"/>
                <a-badge v-if="userInfo.status == 2" status="error" text="辞退"/>
            </a-descriptions-item>
            <a-descriptions-item label="所属部门">{{userInfo.departmentName}}</a-descriptions-item>
            <a-descriptions-item label="角色">{{userInfo.roleName}}</a-descriptions-item>
            <a-descriptions-item label="基本薪资">{{userInfo.baseAmount}}</a-descriptions-item>
            <a-descriptions-item label="操作记录">
                入职办理人：{{userInfo.createName}}
                <br/>
                入职办理时间: {{formatDate(userInfo.createDate,'YYYY-MM-DD HH:mm:ss')}}
                <br/>
                <br/>
                最近信息修改人: {{userInfo.updateName}}
                <br/>
                最近信息修改时间: {{formatDate(userInfo.updateDate,'YYYY-MM-DD HH:mm:ss')}}
            </a-descriptions-item>
        </a-descriptions>
        <template #extra>
            <a-button type="primary" @click="userInfoVisible = false">关闭</a-button>
        </template>
    </a-drawer>
</template>

<script>
    import {ref, onMounted} from 'vue'
    import axios from 'axios'
    import {message, Form} from 'ant-design-vue';
    import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
    import {DownOutlined, UpOutlined} from '@ant-design/icons-vue';
    import dayjs from 'dayjs'
    import {isEmpty} from "@/utils/Tool";

    export default {
        name: "User",
        components: {
            DownOutlined,
            UpOutlined,
        },
        setup() {
            const columns = [
                {
                    title: 'ID',
                    dataIndex: 'id',
                    key: 'id',
                    align: 'center',
                },
                {
                    title: '账号',
                    dataIndex: 'userCode',
                    key: 'userCode',
                    align: 'center',
                },
                {
                    title: '头像',
                    dataIndex: 'pic',
                    key: 'pic',
                    align: 'center'
                },
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                    align: 'center'
                },
                {
                    title: '工号',
                    dataIndex: 'workNum',
                    key: 'workNum',
                    align: 'center',
                },
                {
                    title: '电话号码',
                    dataIndex: 'phone',
                    key: 'phone',
                    align: 'center',
                },
                {
                    title: '生日',
                    dataIndex: 'birthday',
                    key: 'birthday',
                    align: 'center',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    align: 'center'
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    width: '200px'
                }
            ]
            const locale = zhCN
            const user = ref({
                userCode: '',
                username: '',
                phone: '',
                email: '',
                birthday: undefined
            })
            const userInfo = ref({})
            const userList = ref()
            const departmentList = ref([])
            const searchData = ref({})
            const expand = ref(false);
            const pagination = ref({
                current: 1,
                pageSize: 5,
            })
            const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])
            const visible = ref(false);
            const userInfoVisible = ref(false);
            const useForm = Form.useForm
            const {validate, validateInfos, resetFields} = useForm(user, {
                userCode: [{required: true, message: '请输入账号', trigger: ['submit', 'change']}],
                username: [{required: true, message: '请输入用户名', trigger: ['submit', 'change']}],
                phone: [{required: true, message: '电话号码不能为空', trigger: ['submit', 'change']},
                    {
                        pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                        message: '电话号码非法',
                        trigger: ['submit', 'change']
                    }],
                email: [{required: true, message: '邮箱不能为空', trigger: ['submit', 'change']},
                    {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱非法', trigger: ['change']}],
                birthday: [{required: true, message: '请输入生日', trigger: ['submit', 'change']}],
            })

            const saveOrUpdate = () => {
                validate().then(() => {
                    console.log("通过校验")
                    axios.post('/user/saveOrUpdate', user.value).then(rs => {
                        console.log("新增或修改结果：", rs)
                        if (rs.code == 200) {
                            visible.value = false
                            message.success("操作成功")
                            load()
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })
            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/user/deleteById/' + id).then(rs => {
                    if (rs.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.message)
                    }
                })
            }
            const okDismissed = (id) => {
                console.log("要辞退的ID：" + id)
                axios.get('/user/dismissedById/' + id).then(rs => {
                    if (rs.code == 200) {
                        message.success("辞退成功")
                        load()
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const openModal = (obj) => {
                console.log("模态框参数：", obj)
                user.value = JSON.parse(JSON.stringify(obj))
                if (isEmpty(user.value)) {
                    resetFields()
                }
                if (user.value.id != undefined) {
                    user.value.birthday = dayjs(user.value.birthday)
                }
                visible.value = true;
            }

            const load = (pageNum) => {
                pagination.value.current = pageNum == 1 ? 1 : pagination.value.current
                axios.get('/user/queryPageByCondition', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        username: searchData.value.username,
                        userCode: searchData.value.userCode,
                        workNum: searchData.value.workNum,
                        phone: searchData.value.phone,
                        status: searchData.value.status,
                        deptId: searchData.value.deptId
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    userList.value = rs.data.records
                    pagination.value.total = rs.data.total
                })
            }

            const onChange = (pageNum, pageSize) => {
                pagination.value.current = pageNum
                pagination.value.pageSize = pageSize
                load()
            }

            const reset = () => {
                searchData.value = {}
                load()
            }

            const formatDate = (time, format) => {
                return dayjs(time).format(format)
            }

            const getUserInfo = (userId) => {
                console.log("要获取用户详情的id：", userId)
                axios.get('user/getUserInfo/' + userId).then(rs => {
                    userInfo.value = rs.data
                    userInfoVisible.value = true
                })
            }

            onMounted(() => {
                axios.get('department/queryAll').then(rs => {
                    departmentList.value = rs.data
                    departmentList.value.unshift({
                        name: '全部',
                        id: null
                    })
                })
                load()
            })
            return {
                columns,
                user,
                userList,
                pagination,
                pageSizeOptions,
                onChange,
                load,
                locale,
                searchData,
                reset,
                visible,
                openModal,
                saveOrUpdate,
                okDelete,
                expand,
                formatDate,
                getUserInfo,
                userInfoVisible,
                userInfo,
                departmentList,
                okDismissed,
                validateInfos,
                resetFields
            }
        }
    }
</script>

<style scoped>
    .cardContent {
        background: #fff;
        margin: 10px 10px 0 10px;
        padding: 15px;
    }

    .ant-advanced-search-form {
        background: rgba(255, 255, 255, 0.04);
        /*padding: 15px;*/
        border-radius: 2px;
    }
</style>